import { DictValueEnum } from "@/components/DictTag";
import { ModalForm, ProFormRadio, ProFormText } from "@ant-design/pro-components";
import React, { useState } from "react";

export type FormValueType = any & Partial<API.Setting.ResetPasswordBo>;

export type ResetPasswordFormProps = {
	onCancel: () => void;
	onSubmit: (values: FormValueType) => Promise<void>;
	open: boolean;
	types: DictValueEnum;
	userId: number | undefined;
};

const ResetPasswordForm: React.FC<ResetPasswordFormProps> = props => {
	const [type, setType] = useState<string>("Y");
	const { userId, onSubmit = () => {}, onCancel = () => {}, types } = props;

	const handleCancel = () => {
		onCancel();
	};
	const handleFinish = async (values: Record<string, any>) => {
		return await onSubmit({ ...values, id: userId } as FormValueType);
	};

	return (
		<ModalForm<FormValueType>
			width={640}
			title="密码重置"
			open={props.open}
			modalProps={{
				destroyOnClose: true,
				onCancel: handleCancel
			}}
			onFinish={handleFinish}
		>
			<ProFormRadio.Group
				radioType="button"
				name="type"
				label="使用内置密码"
				valueEnum={types}
				initialValue={"Y"}
				rules={[
					{
						required: true,
						message: "确认密码不可为空。"
					}
				]}
				fieldProps={{
					onChange: (event: any) => {
						setType(event?.target?.value);
					}
				}}
			/>
			{type === "N" && (
				<>
					<ProFormText.Password
						name="password"
						label="密码"
						rules={[
							{
								required: true,
								message: "密码不可为空。"
							}
						]}
					/>
					<ProFormText.Password
						name="confirm_password"
						label="确认密码"
						rules={[
							{
								required: true,
								message: "确认密码不可为空。"
							},
							({ getFieldValue }) => ({
								validator(_, value) {
									if (!value || getFieldValue("password") === value) {
										return Promise.resolve();
									}
									return Promise.reject(new Error("两次密码不匹配"));
								}
							})
						]}
					/>
				</>
			)}
		</ModalForm>
	);
};

export default ResetPasswordForm;
